package com.gary.memoryLeak;

import java.util.HashMap;
import java.util.WeakHashMap;

/**
 * 使用虚引用解决缓存引起的内存泄露问题
 * @author peng_rui
 * @date 2022/3/13
 */
public class CacheDemo {
    private static HashMap<String, Object> map = new HashMap<>();
    private static WeakHashMap<String, Object> wMap = new WeakHashMap<>();

    public static void init() {
        String str1 = new String("str1");
        String str2 = new String("str2");
        String str3 = new String("str3");
        String str4 = new String("str4");
        map.put(str1, "cacheStr1");
        map.put(str2, "cacheStr2");
        wMap.put(str3, "cacheStr3");
        wMap.put(str4, "cacheStr4");
    }

    public static void main(String[] args) {
        init();

        System.out.println("GC前 map中");
        map.forEach((key, value) -> {
            System.out.println(key + " : " + value);
        });

        System.out.println("GC前 wMap中");
        wMap.forEach((key, value) -> {
            System.out.println(key + " : " + value);
        });

        System.gc();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("GC后 map中");
        map.forEach((key, value) -> {
            System.out.println(key + " : " + value);
        });

        System.out.println("GC后 wMap中");
        wMap.forEach((key, value) -> {
            System.out.println(key + " : " + value);
        });

    }

}
